/* eslint-disable no-loop-func */
import { insertJQuery } from '../../lib/utils.js';

class FileUploadHelper {
  /**
   * 文件上传
   * @param blob 文件
   * @param baseInfo 基础信息
   * @returns {Promise}
   */
  importFile(blob, baseInfo) {
    return new Promise(async (resolve, reject) => {
      let formData = await this.getImportFileParams(blob, baseInfo);
      $.ajax({
        url: 'https://cqxgm.cqsw.gov.cn:7005/WLSB/servlet/ImportFile',
        type: 'post',
        data: formData,
        processData: false,
        contentType: false,
        success: async function(responseStr) {
          resolve(await this.getResult(this.getIDFromHtml(responseStr)));
        },
        error: function(responseStr) {
          resolve('国税系统错误！网络存在异常！');
        }
      }).fail(function(err) {
        console.error(err);
        resolve('国税系统错误！网络存在异常！');
      });
    });
  }

  /**
   * 对返回的html处理 获得唯一ID
   * @param html
   * @returns {*}
   */
  getIDFromHtml(html) {
    let matchArray = html.match(/(ID = (\d+))/);
    if (matchArray && matchArray[2]) {
      return matchArray[2];
    }
    console.error(html);
    return '';
  }

  /**
   * 获取文件上传接口参数
   * @param blob
   * @param baseInfo
   * @returns {Promise.<*>}
   */
  async getImportFileParams(blob, baseInfo) {
    // todo 中文编码问题
    // let importFileFormHtml = `<form id="importFileForm" style="display:none" enctype="multipart/form-data" accept-charset="UTF-8">
    //        <input type="hidden" class="NSRMC" name="NSRMC">
    //        <input type="hidden" class="CWBB_MC" name="CWBB_MC">
    //      </form>`;
    // $('body').append(importFileFormHtml);
    // $('#importFileForm .NSRMC').val(baseInfo.nsrmc);
    // $('#importFileForm .CWBB_MC').val(baseInfo.szmc);
    // let formData = new FormData($('#importFileForm')[0]);
    let formData = new FormData();
    let file = new Blob([blob], { type: 'application/zip' });
    let fileName = this.getFileName(baseInfo);
    formData.append('file', file, fileName);
    formData.append('NSRSBH', baseInfo.nsrsbh);
    // formData.append("NSRMC", baseInfo.nsrmc);
    formData.append('NSRMC', await this.gbk2uf8(baseInfo.nsrmc, 'iso8859-1'));
    formData.append('CWBB_TYPE', baseInfo.szdm);
    // formData.append("CWBB_MC", baseInfo.szmc);
    formData.append('CWBB_MC', await this.gbk2uf8(baseInfo.szmc, 'iso8859-1'));
    formData.append('SSQQ', baseInfo.skssqq.replace(/-/g, ''));
    formData.append('SSQZ', baseInfo.skssqz.replace(/-/g, ''));
    formData.append('SBFS', baseInfo.sbfs);
    formData.append('DJXH', baseInfo.djxh);
    return formData;
  }

  /**
   * 转码
   * @param str
   * @returns {Promise}
   */
  gbk2uf8(str, code = 'GBK') {
    return new Promise(resolve => {
      let reader = new FileReader();
      reader.onload = function(event) {
        resolve(event.target.result);
      };
      let blob = new Blob([str]);
      reader.readAsText(blob, code);
    });
  }

  /**
   * 获取文件名称
   * @param baseInfo
   * @returns {string}
   */
  getFileName(baseInfo) {
    // 文件名例子 "CWBB06_91500106MA5YQUQC4E_20180301_20180331.zip"
    let fileName = `CWBB${baseInfo.szdm}_${
      baseInfo.nsrsbh
    }_${baseInfo.skssqq.replace(/-/g, '')}_${baseInfo.skssqz.replace(
      /-/g,
      ''
    )}.zip`;
    console.log(fileName);
    return fileName;
  }

  /**
   * 获取文件上传处理结果
   * 这里采用了轮询的方式 直到文件处理（1.成功 2.失败 3.超过指定次数) 才返回结果
   * @param ID
   * @param count
   * @returns {*}
   */
  getResult(ID, count = 20) {
    if (count <= 0) {
      return Promise.resolve('文件处理超时！请重新申报！');
    }
    if (!ID) {
      return Promise.resolve('国税系统异常！请稍后再试！');
    }
    console.log(count);
    return new Promise((resolve, reject) => {
      let json = {};
      json.SYS_ClassName = 'com.taxware.WLSBBS.WLSBBS.TTAX_CWBB_IMP';
      json.SYS_EventName = 'uf_GetRet';
      json.ID = ID;
      $.post('../UIRequest_AJAX', json, async function(data, status) {
        json = JSON.parse(data);
        if (json.STATE === '1' || json.STATE === '2') {
          console.log('文件正在处理中，请稍候...');
          resolve(this.delay(this.getResult(ID, --count), 100));
        }
        if (json.STATE === '3') {
          // 刷新当前页面 链接中SBID有变化 替换对应数字
          let link = $('#indexContent')[0].src;
          let matchArray = link.match(/SBID=(\d+)/);
          if (matchArray) {
            link = link.replace(matchArray[1], json.SBID);
          }
          $('#indexContent')[0].src = link;
          resolve('三大报表导入数据成功！请审查后申报！');
        }

        resolve(await this.getErrorMsg(ID));
      });
    });
  }

  /**
   * 延迟函数执行时间
   * @param delayFunc
   * @param time
   */
  delay(delayFunc, time) {
    let timer = setTimeout(function() {
      clearTimeout(timer);
      delayFunc;
    }, time);
  }

  /**
   * 获取错误信息
   * @returns {Promise}
   */
  getErrorMsg(id) {
    return new Promise(resolve => {
      $.ajax({
        url: 'https://cqxgm.cqsw.gov.cn:7005/WLSB/UIRequest_AJAX',
        type: 'post',
        data: {
          SYS_ClassName: 'com.taxware.WLSBBS.WLSBBS.TTAX_CWBB_IMP',
          SYS_EventName: 'uf_GetMsg',
          ID: id
        },
        headers: {
          'Access-Control-Allow-Origin': '*'
        },
        dataType: 'html',
        success: function(data) {
          let result = JSON.parse(data);
          console.log(result.ret_msg);
          resolve('填报失败! ' + result.ret_msg);
        }
      }).fail(function(err) {
        console.log(err);
        resolve('填报失败! 国税系统错误！网络存在异常！');
      });
    });
  }
}

// 同步申报表信息及申报表
class SyncReportInfoHelper {
  /**
   * 抓取待办事项
   */
  captureTodo() {
    const iframeWindow = window
      .jQuery('iframe:visible')[0]
      .contentWindow.window.jQuery('iframe:visible')[0].contentWindow;
    const $ = iframeWindow.$;
    const trs = $('.datagrid-btable tbody tr').toArray();
    return trs.map(tr => {
      const tds = $(tr)
        .find('td:visible')
        .toArray();
      let declareType = tds
        .find(td => $(td).attr('field') === 'YZPZZL_MC')
        .innerText.trim();

      if (declareType.includes('企业所得税')) {
        const period = tds
          .find(td => $(td).attr('field') === 'NSQX_MC')
          .innerText.trim();
        declareType += /季|月/.test(period) ? '月(季)' : '年';
      }

      if (declareType.includes('适用执行') || !declareType) {
        declareType = `财务报表(${declareType})`;
      }
      declareType = this.replaceSpecialSign(declareType);
      const SBRQ = tds.find(td => $(td).attr('field') === 'SBRQ');
      const declareTime = SBRQ ? SBRQ.innerText.trim() : '';
      const state = tds
        .find(td => $(td).attr('field') === 'ZTMC')
        .innerText.trim()
        .includes('已')
        ? '已申报'
        : '未申报';
      return {
        declareTime,
        declareType,
        state
      };
    });
  }

  /**
   * 从页面中获取报表信息
   */
  async captureDataFromPage() {
    let retryCount = 2;
    let reportInfoFromTodo = this.captureTodo();
    const _this = this;
    const now = new Date().getTime();
    while (retryCount && !reportInfoFromTodo.length) {
      // eslint-disable-next-line no-await-in-loop
      await new Promise((resolve, reject) => {
        setTimeout(function() {
          reportInfoFromTodo = _this.captureTodo();
          retryCount -= 1;
          resolve();
        }, 2000);
      });
    }
    // console.log('spend time', new Date().getTime() - now);
    // console.log('success', reportInfoFromTodo);
    if (!reportInfoFromTodo.length) {
      // alert('请本期申报完成后，再同步申报表信息！');
    }
    window.postMessage(
      {
        event: 'syncReportInfoInSaas',
        data: {
          syncReportInfo: reportInfoFromTodo
        }
      },
      '*'
    );
  }

  /**
   * 开始同步申报表信息
   */
  startGetReportInfo() {
    // const button = $('.be1').toArray().find(item => $(item).text().includes('应申报'));
    if (
      !/https:\/\/etax.chongqing.chinatax.gov.cn\//.test(window.location.href)
    ) {
      alert('请在首页进行同步申报种类！');
      return;
    }
    // button.click();
    $.ajax({
      url:
        'https://etax.chongqing.chinatax.gov.cn/download.sword?ctrl=LogindesCtrl_queryKeyValue',
      type: 'post',
      data: {
        url: 'null',
        wbxtDm: 'F251000200000176',
        qxDm: '102230'
      },
      dataType: 'json',
      success: function(resData) {
        console.log(resData);
        let keyValue = resData.key;
        let reUrl = resData.reUrl;
        let param = '';
        let url = '';
        if (keyValue != '') {
          param = 'cssParam=' + encodeURIComponent(keyValue) + '&xtBz=WSBS&';
        }
        if (reUrl != '') {
          url = reUrl;
        }
        url = url + '&' + param + 'r=' + Math.random();
        window.open(decodeURI(url));
      }
    }).fail(function(err) {
      console.log(err);
    });
  }

  /**
   * 开始同步申报表
   */
  async startGetReport() {
    let iframeWindow;

    const href = window.location.href;
    const isInHistoryPage = href.includes(
      'https://etax.chongqing.chinatax.gov.cn:8002'
    );

    // 增值税、附加税
    const isInReportPage = /\/WLSB\/WLSBBS\/TTAX_index.html\?MODULE=TTAX_SB_([A-Z]{2,5}).html/.test(
      href
    );

    // 应申报查看界面 所得税 附加税
    const isInSdsPage = /etax.chongqing.chinatax.gov.cn:6011\/form.sword/.test(
      href
    );

    try {
      if (isInHistoryPage) {
        // 去除查询倒计时
        window.second_SB = 0;
        // 查询历史填报数据界面
        iframeWindow = $('iframe:visible')[0].contentWindow.$(
          'iframe:visible'
        )[0];
      } else if (isInSdsPage) {
        iframeWindow = { contentWindow: window };
      } else {
        // 申报查看界面
        iframeWindow = $('#indexContent')
          .contents()
          .find('#Layout_PZZL_center iframe:visible')[0];
      }
    } catch (e) {
      console.error(e);
    }

    if (!(isInReportPage || isInHistoryPage || isInSdsPage) || !iframeWindow) {
      alert('请到对应的申报界面进行同步申报表');
      return;
    }

    iframeWindow = iframeWindow.contentWindow;
    let tables;
    let jq;
    if (isInHistoryPage) {
      tables = iframeWindow.$('table table');
    } else if (isInSdsPage) {
      // eslint-disable-next-line no-undef
      await insertJQuery();
      // eslint-disable-next-line no-undef
      jq = jQuery;
      tables = jq('.tab_form:visible');
    } else {
      tables = iframeWindow.$('table');
    }
    tables = tables.toArray();

    const result = [...tables].map(table =>
      this.transformTableToArray(table, jq, isInSdsPage));
    console.log(result);
    let declareType = (isInHistoryPage
      ? iframeWindow.$('h3').text()
      : result[0][0][0].val
    )
      .trim()
      .replace('城市维护建设税', '城建税');
    if (isInSdsPage) {
      // eslint-disable-next-line no-undef
      declareType = jQuery('#headerTitle')
        .text()
        .trim();
    }
    declareType = this.replaceSpecialSign(declareType);
    declareType = this.replaceName(declareType);
    window.postMessage(
      {
        event: 'syncReportInSaas',
        data: {
          detail: result,
          state: '已申报',
          declareType
        }
      },
      '*'
    );
  }

  /**
   * 将dom转换为二维数组
   * @param {Array} table
   * @param {Object} $
   * @param {Boolean} isInSdsPage
   */
  transformTableToArray(table, $ = window.$, isInSdsPage) {
    // 集合所有tr即每一行
    const trs = $(table)
      .find('tr:visible')
      .toArray();

    // 构建二维数组，并构建每一行每一列的数据
    const result = trs.map(tr => {
      let tds = $(tr)
        .find('td:visible')
        .toArray();
      isInSdsPage
        && (tds = $(tr)
          .find('th,td')
          .toArray());
      if (tds && tds.length) {
        tds = tds.map(td => {
          const $td = $(td);
          const inputs = $td.find('input');
          let val = '';
          // 若存在input，则为输入框
          if (inputs.length) {
            // 获取输入
            val = $(inputs[0]).val();
            if (['N', 'Y'].includes(val)) {
              val = val === 'N' ? '否' : '是';
            }
            let text = $td.text().replace(/\s/g, '');
            // 存在文本+输入框情况 需都抓取 排除-- （数额为空填充）
            if (text && text !== '--') {
              val = text + val;
            }
          } else {
            val = $td.text().replace(/\s/g, '');
          }
          // return val;
          return {
            val,
            rowspan: $td.attr('rowspan') || '1',
            colspan: $td.attr('colspan') || '1'
          };
        });
      }
      return tds;
    });
    return result;
  }

  /**
   * 替换特殊符号
   * @param {String} str
   */
  replaceSpecialSign(str) {
    return str.replace(/（/g, '(').replace(/）/g, ')');
  }

  replaceName(name) {
    const names = [
      '企业所得税月', '企业所得税年', '增值税', '个人所得税', '财务报表', '附加税'
    ];
    return names.find(n => name.includes(n));
  }
}

const syncReportInfoHelper = new SyncReportInfoHelper();
const fileUploadHelper = new FileUploadHelper();

export { syncReportInfoHelper, fileUploadHelper };
